package etxt2db.corpus;
import java.io.IOException;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.aliasi.chunk.Chunk;
import com.aliasi.chunk.ChunkFactory;
import com.aliasi.chunk.ChunkingImpl;
import com.aliasi.corpus.ChunkHandler;

import edu.cmu.minorthird.text.Span;
import edu.cmu.minorthird.text.TextLabels;


public class LingpipeHMMTrainer {
	
	private ChunkHandler mHandler;
	
	List<String> attributes;
	
    
    public LingpipeHMMTrainer(List<String> attributes) throws IOException {
    	this.attributes = attributes;
    }

    public LingpipeHMMTrainer(ChunkHandler handler, List<String> attributes) 
        throws IOException {
        mHandler = handler;
        this.attributes = attributes;
    }
    

    /**
     * Returns the chunk handler for this parser.
     *
     * @return The chunk handler.
     */
    public ChunkHandler getChunkHandler() {
        return getHandler();
    }

    public void parse(TextLabels file) throws ParseException {
    	Iterator<Span> iter = file.getTextBase().documentSpanIterator();
    	while(iter.hasNext()){
    		Span s = iter.next();
    		ChunkingImpl chunking = new ChunkingImpl(s.asString());
    		for(String att : attributes){
    			Set<Span> classified = file.getTypeSet(att, s.getDocumentId());
    			for(Span classifiedSpan : classified){
    				int loChar = classifiedSpan.getLoChar()-s.getLoChar();
    				int hiChar = classifiedSpan.getHiChar()-s.getLoChar();
    				Chunk chunk = ChunkFactory.createChunk(loChar,hiChar,att);
    				chunking.add(chunk);
    			}
    		}
     		getChunkHandler().handle(chunking);
    	}
    }
    
    public void setHandler(ChunkHandler handler) {
        mHandler = handler;
    }
    
    public ChunkHandler getHandler() {
        return mHandler;
    }
    
    static final int MAX_N_GRAM = 8;
    static final int NUM_CHARS = 256;
    static final double LM_INTERPOLATION = MAX_N_GRAM; // default behavior
}